﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace IceDog.DNC.Program.WebApi.CustomMiddleware
{
    public static class StopWatchMiddlewareExtensions
    {
        public static IApplicationBuilder UseStopWatch(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<StopWatchMiddleware>();
            //这样写可以省去注入StopWatch
            //services.AddTransient<Stopwatch>();
            //return builder.UseMiddleware<StopWatchMiddleware>(new Stopwatch());
        }
    }

    public class StopWatchMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly Stopwatch _stopwatch;
        public StopWatchMiddleware(RequestDelegate next,Stopwatch stopwatch)
        {
            _next = next;
            _stopwatch = stopwatch;
        }
        public async Task Invoke(HttpContext context)
        {
            _stopwatch?.Start();
            await _next(context);
            _stopwatch.Stop();
            await context.Response.WriteAsync($"<div>total cost ms:{_stopwatch.ElapsedMilliseconds}</div>");
        }
    }
}
